﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using edowork.com.SQL2005;

namespace WebInvoicingsys.system.storage.stockbill
{
    public partial class stockbill_in_check : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0";

        //传入的参数
        string id, start_date, end_date, billsno;


        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                id = Request.Params["id"].ToString();
                start_date = Request.Params["start_date"].ToString();
                end_date = Request.Params["end_date"].ToString();
                billsno = Request.Params["billsno"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 绑定单据主信息
        /// </summary>
        /// <returns></returns>
        private void BindInfo()
        {
            Execute exec = new Execute(Session["connectionString"].ToString());

            string sql = "", error_msg = "";

            //构造SQL语句
            sql = @"select a.billsno, a.APPID, a.billdate, a.remark, 
                           a.shipto,
                           (select warehouse.warehousename from warehouse where warehouse.warehouseid=a.shipto) shiptoname,
                           b.arrivaldate,
                           b.supplierid,
                           (select supplier.suppliername from supplier where supplier.supplierid=b.supplierid) suppliername,
                           b.phone,
                           b.fax,
                           a.checkremark
                      from bills a, purchase b
                       where a.APPID=b.pcsid
                         and a.billsno='{0}'";


            sql = String.Format(sql, id);

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if ((ds == null) || (ds.Tables.Count <= 0) || (ds.Tables[0].Rows.Count <= 0))
            {
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_APPID.Text = dr["APPID"].ToString();
                txt_BillDate.Text = dr["billdate"].ToString();
                txt_suppliername.Text = dr["suppliername"].ToString();
                txt_arrivaldate.Text = dr["arrivaldate"].ToString();
                txt_phone.Text = dr["phone"].ToString();
                txt_fax.Text = dr["fax"].ToString();
                txt_shipto.Text = dr["shiptoname"].ToString();
                txt_remark.Text = dr["remark"].ToString();

                txt_checkremark.Text = dr["checkremark"].ToString();
            }
        }

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("id");
            dtList.Columns.Add("areaname");
            dtList.Columns.Add("storagename");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");

            DataTable dtData = ((purchasein_putin_class)Session["purchasein_putin"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["id"] = dr["id"].ToString();
                drnew["areaname"] = dr["areaname"].ToString();
                drnew["storagename"] = dr["storagename"].ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty1"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParma();

                try
                {
                    ((purchasein_putin_class)Session["purchasein_putin"]).Reset();
                }
                catch
                {
                    Session.Add("purchasein_putin", new purchasein_putin_class(Session["connectionString"].ToString()));
                }
                finally
                {
                    ((purchasein_putin_class)Session["purchasein_putin"]).getDataList(id);
                }

                BindInfo();

                Bind();

                Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //更新主表的审批备注
                sql = "update bills set checkremark='{1}' where billsno='{0}' and checkstu='0' and m_stu='0'";

                sql = String.Format(sql, id, txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "仓库单备注保存失败，错误原因：仓库单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                tran.Commit();
                tranutil.CloseConnection();
            }

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            GetParma();

            string url = "/system/storage/stockbill/stockbill_in_list.aspx?start_date={0}&end_date={1}&billsno={2}";

            url = String.Format(url, start_date, end_date, billsno);

            Response.Redirect(url);
        }

        //审核
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "", error_msg="";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(txt_BillDate.Text.Trim()).ToString("yyyy"), DateTime.Parse(txt_BillDate.Text.Trim()).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查是否存在盘点单
                sql = String.Format("select csid from check_stock where warehouseid=(select shipto from bills where billsno='{0}') and checkstu='0'", id);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前仓库正在盘点，不能进行出入库操作。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //锁定所有需操作的表资源，同时写入不存在仓库库存表中的库存产品，写入库存流水，更新库存数量
                sql = String.Format("exec sys_stockbill_in_locktable '{0}'", id);

                dsResult = exec.ExecStoreProcQueryDataSet(sql, ref error_msg, tran);

                if (dsResult == null)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, error_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //更新仓库单审核人员信息
                sql = "update bills set checkuserid='{1}', checkstu='1', Checkdate='{2}', checkremark='{3}' where billsno='{0}' and m_stu='0' and checkstu='0'";

                sql = String.Format(sql, id, Session["userid"].ToString(), DateTime.Now.ToString("yyyy-MM-dd"), txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref error_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "仓库单审批失败，错误原因：仓库单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                tran.Commit();
                tranutil.CloseConnection();
            }


            alert_msg = String.Format(Scripts.alert_success, Errormsg.stockbill_in_check_success);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }
    }
}